import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_picker/Picker.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/style/default_style.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:flutter_pickers/time_picker/model/pduration.dart';
import 'package:flutter_pickers/time_picker/model/suffix.dart';
import 'package:get/get.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/my/page/set/details_web_page.dart';
import 'package:nft_shop/net/dio_api.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/util/textfield_inputnum_utils.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/my_app_bar.dart';
import 'package:nft_shop/widgets/my_button.dart';
import 'package:nft_shop/widgets/my_scroll_view.dart';

class MyResellPage extends StatefulWidget {
  MyGoodsSpecialModel model;
  bool isBooking;

  MyResellPage({Key? key, required this.model, this.isBooking = false})
      : super(key: key);

  @override
  _MyResellPageState createState() => _MyResellPageState();
}

class _MyResellPageState extends State<MyResellPage> {
  final TextEditingController _controller = TextEditingController();
  final FocusNode _focus = FocusNode();
  MemberExtendModel extendModel = MemberExtendModel();
  FeeConfigModel feeModel = FeeConfigModel();
  bool _isCalculate = false;
  bool isCheck = false;

  String timeText = DateUtil.formatDateStr(DateUtil.getNowDateStr(),
      format: "yyyy-MM-dd HH:mm");

  //单个作品 //多个作品
  bool isSingle = true;

  //是否预售
  bool isPresell = true;

  //开售时间
  String time = "";

  //实践转化
  String times = "";

  late Picker picker;

  PDuration? startDuration;

  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  bool get isCalculate => _isCalculate;

  set isCalculate(bool value) {
    _isCalculate = value;
    setState(() {});
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    isPresell = widget.isBooking;
    startDuration = PDuration.parse(DateTime.parse(timeText));
    getmemberExtend();
    getConfigName();
  }

  //平台结算服务费 trilateral_platform_fee，
  //支付通道费 aisle_fee，
  //链上手续费 chain_fee，
  //平台手续费 platform_fee，
  //三方平台转账手续费 trilateral_platform_transfer_fee,
  Future<void> getConfigName() async {
    try {
      feeModel = await ServiceRepository.getFeeConfig();
    } catch (e, s) {}
  }

  void getmemberExtend() async {
    try {
      EasyLoading.show(status: "加载中");
      extendModel = await ServiceRepository.memberExtend();
      setState(() {});
      EasyLoading.dismiss();
    } catch (e, s) {}
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        FocusScope.of(context).requestFocus(new FocusNode());
        if (picker != null) {
          picker.doCancel(context);
        }
      },
      child: Scaffold(
        key: _scaffoldKey,
        appBar: MyAppBar(
          centerTitle: "转售商品",
        ),
        body: MyScrollView(
          children: [
            paymentAccount(),
            Container(
              color: Global.kTheme.colorLine,
              height: 5,
            ),
            goodsView(),
            Container(
              color: Global.kTheme.colorLine,
              height: 5,
            ),
            Visibility(
              visible: widget.isBooking,
              child: Column(
                children: [
                  // int.parse(widget.model.allCount??"0") >1 ?optionViewItem(title: "作品数量",left: "单个作品",right: "多个作品",isLeft: isSingle):Container(),
                  optionViewItem(
                      title: "是否预售", left: "是", right: "否", isLeft: isPresell),
                  isPresell
                      ? selectTextItem(
                          "开售时间",
                          time.length != 0 ? time : "请选择开售时间",
                          Global.kTheme.textPrimary12, onPressed: () {
                          print("点击了");
                          showPickerDateTime(context);

                          // Pickers.showDatePicker(
                          //   context,
                          //   // 模式，详见下方
                          //   mode: DateMode.YMDHM,
                          //   // 后缀 默认Suffix.normal()，为空的话Suffix()
                          //   suffix: Suffix(years: ' 年', month: ' 月', days: ' 日', hours:' 时',minutes:' 分'),
                          //   // 样式  详见下方样式
                          //   pickerStyle: DefaultPickerStyle(),
                          //   // 默认选中
                          //   selectDate: PDuration.now(),
                          //   minDate: PDuration(year: startDuration!.year,month: startDuration!.month,day:startDuration!.day),
                          //   onConfirm: (p) {
                          //     setState(() {
                          //       startDuration = p;
                          //       time = "${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}";
                          //     });
                          //     print('longer >>> 返回数据：$p');
                          //   },
                          //   // onChanged: (p) => print(p),
                          // );
                        })
                      : Container(),
                ],
              ),
            ),
            priceView(),
          ],
          bottomButton: Container(
            height: 110,
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
            decoration: BoxDecoration(
                border: Border(
              top: Divider.createBorderSide(context,
                  color: Global.kTheme.colorLine, width: 1),
            )),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                InkWell(
                  onTap: () {
                    setState(() {
                      isCheck = !isCheck;
                    });
                  },
                  child: Text.rich(
                    TextSpan(children: [
                      WidgetSpan(
                          child: Icon(
                        isCheck
                            ? Icons.check_box
                            : Icons.check_box_outline_blank_sharp,
                        size: 18,
                      )),
                      TextSpan(
                          text: "点击确认出售则视为同意",
                          style: TextStyle(
                            fontSize: 12,
                            color: Color(0xFFA0A0A0),
                          )),
                      WidgetSpan(
                          child: InkWell(
                        onTap: () {
                          Get.to(DetailsWebPage(
                            name: "数字资产交易服务条款",
                          ));
                        },
                        child: Text(
                          "《数字资产交易服务条款》",
                          style: TextStyle(
                            fontSize: 12,
                            color: Color(0xFF5F7EA3),
                          ),
                        ),
                      ))
                    ]),
                    textAlign: TextAlign.center,
                  ),
                ),
                SizedBox(
                  height: 14,
                ),
                Container(
                  height: 40,
                  decoration: BoxDecoration(
                    color: Global.kTheme.colorBackground3,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: MyButton(
                    minHeight: 40,
                    onPressed: () async {
                      _focus.unfocus();

                      if (!isCheck) {
                        EasyLoading.showToast("请勾选协议");
                        return;
                      }

                      if (_controller.text.length == 0) {
                        EasyLoading.showToast("请输入您要的售卖价格");
                        return;
                      }

                      if (isPresell && times.length == 0) {
                        EasyLoading.showToast("请选择预售时间");
                        return;
                      }

                      int tims = DateUtil.getDateMsByTimeStr(times) ?? 0;
                      if (isPresell && (tims < DateUtil.getNowDateMs())) {
                        EasyLoading.showToast("选择预售时间需要比现在时间大");
                        return;
                      }

                      EasyLoading.show(status: "加载中...");
                      try {
                        print(
                            "点击的---- ${widget.model.type}---${JsonUtil.encodeObj(widget.model)}");
                        //type类型 类型 1整体藏品 2整体盲盒 3专辑 4藏品 5盲盒未拆 6盲盒已拆
                        if (widget.model.type == 1) {
                          await ServiceRepository.specialChange(
                              widget.model.specialId ?? "",
                              _controller.text,
                              isPresell ? "1" : "0",
                              time: time);
                        } else if (widget.model.type == 2) {
                          await ServiceRepository.specialMangChange(
                              widget.model.specialId ?? "",
                              _controller.text,
                              isPresell ? "1" : "0",
                              time: time);
                        } else if (widget.model.type == 4 ||
                            widget.model.type == 5 ||
                            widget.model.type == 6) {
                          await ServiceRepository.goodsChange(
                              widget.model.goodsId ?? "", _controller.text);
                        }
                        EasyLoading.showToast("成功");
                        Get.back();
                      } catch (e, s) {
                        EasyLoading.showToast(http.setError(e, s));
                      }
                    },
                    text: "确认出售",
                    fontSize: 16,
                    textColor: Colors.white,
                    backgroundColor: Global.kTheme.colorBackground3,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  showPickerDateTime(BuildContext context) {
    picker = Picker(
        adapter: DateTimePickerAdapter(
          type: PickerDateTimeType.kYMDHM,
          isNumberMonth: true,
          yearSuffix: "年",
          monthSuffix: "月",
          daySuffix: "日",
          hourSuffix: "时",
          minuteSuffix: "分",
          minValue: DateTime.now(),
          //minHour: 1,
          //maxHour: 23,
          // twoDigitYear: true,
        ),
        cancelText: "取消",
        cancelTextStyle:
            TextStyle(fontSize: 16, color: Global.kTheme.textPrimary6),
        confirmText: "确认",
        confirmTextStyle:
            TextStyle(fontSize: 16, color: Global.kTheme.textPrimary6),
        textAlign: TextAlign.right,
        selectedTextStyle: TextStyle(color: Colors.blue),
        footer: Container(
          height: 50.0,
          alignment: Alignment.center,
        ),
        onConfirm: (Picker picker, List value) {
          print(picker.adapter.text);
          setState(() {
            times = picker.adapter.text;
            time = DateUtil.formatDateStr(picker.adapter.text,
                format: "yyyy-MM-dd HH:mm:ss");
          });
        },
        onSelect: (Picker picker, int index, List<int> selected) {});

    picker.showModal(context);
  }

  //收款账号
  Widget paymentAccount() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "收款账号",
            style: TextStyle(
                fontSize: 14,
                color: Global.kTheme.textPrimary4,
                fontFamily: Global.mySemiboldFont),
          ),
          SizedBox(
            height: 10,
          ),
          Row(
            children: [
              Expanded(
                flex: 1,
                child: Text.rich(TextSpan(children: [
                  TextSpan(
                      text: "支付宝名称",
                      style: TextStyle(
                          fontSize: 13,
                          color: Global.kTheme.inputHint1,
                          fontFamily: Global.mySemiboldFont)),
                  WidgetSpan(
                      child: SizedBox(
                    width: 3,
                  )),
                  TextSpan(
                      text: extendModel.alipayName ?? "",
                      style: TextStyle(
                          fontSize: 13,
                          color: Global.kTheme.textPrimary4,
                          fontFamily: Global.mySemiboldFont)),
                ])),
              ),
              Expanded(
                flex: 1,
                child: Text.rich(TextSpan(children: [
                  TextSpan(
                      text: "支付宝账号",
                      style: TextStyle(
                          fontSize: 13,
                          color: Global.kTheme.inputHint1,
                          fontFamily: Global.mySemiboldFont)),
                  WidgetSpan(
                      child: SizedBox(
                    width: 3,
                  )),
                  TextSpan(
                      text: extendModel.alipayAccount ?? "",
                      style: TextStyle(
                          fontSize: 13,
                          color: Global.kTheme.textPrimary4,
                          fontFamily: Global.mySemiboldFont)),
                ])),
              ),
            ],
          ),
          SizedBox(
            height: 8,
          ),
          Text(
            "转售成功后的收入将直接结算至以上的收款账号",
            style: TextStyle(fontSize: 11, color: Global.kTheme.inputHint1),
          )
        ],
      ),
    );
  }

  //出售商品
  Widget goodsView() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "出售商品",
            style: TextStyle(
                fontSize: 14,
                color: Global.kTheme.textPrimary4,
                fontFamily: Global.mySemiboldFont),
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: LoadImage(
                    widget.model.thumb ?? "",
                    width: 80,
                    height: 80,
                  )),
              SizedBox(
                width: 13,
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    widget.model.title ?? "",
                    style: TextStyle(
                        fontSize: 14,
                        color: Global.kTheme.textPrimary4,
                        fontFamily: Global.mySemiboldFont),
                  ),
                  SizedBox(
                    height: 6,
                  ),
                  Text(
                    "数量 ${widget.model.allCount ?? "1"}",
                    style: TextStyle(
                        fontSize: 13,
                        color: Global.kTheme.inputHint1,
                        fontFamily: Global.mySemiboldFont),
                  ),
                  SizedBox(
                    height: 7,
                  ),
                  Text(
                    "链上标识 ${widget.model.chainMark ?? "--"}",
                    style: TextStyle(
                        fontSize: 13,
                        color: Global.kTheme.inputHint1,
                        fontFamily: Global.mySemiboldFont),
                  ),
                ],
              )
            ],
          )
        ],
      ),
    );
  }

  //作品数量
  Widget optionViewItem(
      {String? title, String? left, String? right, bool isLeft = false}) {
    return Container(
      padding: EdgeInsets.only(left: 15),
      height: 61,
      decoration: BoxDecoration(
          border: Border(
        bottom: Divider.createBorderSide(context,
            color: Global.kTheme.colorLine, width: 1),
      )),
      child: Row(
        children: [
          Expanded(
            flex: 1,
            child: Text(
              title ?? "",
              style: TextStyle(
                fontSize: 14,
                color: Global.kTheme.textPrimary6,
              ),
            ),
          ),
          SizedBox(
            width: 30,
          ),
          Expanded(
            flex: 1,
            child: TextButton(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  LoadAssetImage(
                    isLeft ? "select_image" : "uncheck_image",
                    width: 16,
                    height: 16,
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Text(
                    left ?? "",
                    style: TextStyle(
                        fontSize: 14,
                        color: Global.kTheme.textPrimary1,
                        fontFamily: Global.mySemiboldFont),
                  ),
                ],
              ),
              onPressed: () {
                setState(() {
                  if (title == "作品数量") {
                    isSingle = true;
                  } else if (title == "是否预售") {
                    isPresell = true;
                  }
                });
              },
            ),
          ),
          SizedBox(
            width: 20,
          ),
          Expanded(
            flex: 1,
            child: TextButton(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  LoadAssetImage(
                    isLeft ? "uncheck_image" : "select_image",
                    width: 16,
                    height: 16,
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Text(
                    right ?? "",
                    style: TextStyle(
                        fontSize: 14,
                        color: Global.kTheme.textPrimary1,
                        fontFamily: Global.mySemiboldFont),
                  ),
                ],
              ),
              onPressed: () {
                setState(() {
                  if (title == "作品数量") {
                    isSingle = false;
                  } else if (title == "是否预售") {
                    isPresell = false;
                  }
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  //item 箭头
  Widget selectTextItem(String title, String content, Color color,
      {VoidCallback? onPressed}) {
    return InkWell(
      onTap: onPressed,
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 15),
        height: 61,
        decoration: BoxDecoration(
            border: Border(
          bottom: Divider.createBorderSide(context,
              color: Global.kTheme.colorLine, width: 1),
        )),
        child: Row(
          children: [
            Text(
              title,
              style: TextStyle(
                fontSize: 14,
                color: Global.kTheme.textPrimary6,
              ),
            ),
            Spacer(),
            Text(
              content,
              style: TextStyle(
                  fontSize: 14, color: color, fontWeight: FontWeight.w600),
            ),
            SizedBox(
              width: 7,
            ),
            if (onPressed != null)
              LoadAssetImage(
                "next_icon",
                width: 7,
                height: 12,
              ),
          ],
        ),
      ),
    );
  }

  //设置单价
  Widget priceView() {
    return Container(
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 13),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "设置单价",
              style: TextStyle(
                  fontSize: 14,
                  color: Global.kTheme.textPrimary4,
                  fontFamily: Global.mySemiboldFont),
            ),
            SizedBox(
              height: 15,
            ),
            Container(
              height: 35.0,
              width: double.infinity,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(4),
                border: Border.all(width: 1, color: Color(0xFFE0E0E0)),
              ),
              child: TextField(
                key: const Key('search_text_field'),
//          autofocus: true,
                autocorrect: true,
                //是否自动更正
                controller: _controller,
                focusNode: _focus,
                maxLines: 1,
                inputFormatters: [
                  NumLengthInputFormatter(decimalLength: 2, integerLength: 100),
                ],
                textInputAction: TextInputAction.search,
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                onSubmitted: (String val) {},
                onChanged: (value) {
                  print("输入监听----${value}");
                  if (value.length == 0) {
                    isCalculate = false;
                  } else {
                    isCalculate = true;
                  }
                },
                decoration: InputDecoration(
                  contentPadding: const EdgeInsets.only(
                      top: 0.0, left: 10.0, right: -16.0, bottom: 14.0),
                  border: InputBorder.none,
                  hintText: "请输入您要售卖的价格",
                  suffixIcon: Padding(
                    padding: const EdgeInsets.only(
                        right: 10.0, top: 8.0, bottom: 8.0),
                    child: Text(
                      "¥",
                      textAlign: TextAlign.end,
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(
              height: 10,
            ),
            Visibility(
              visible: isCalculate ? true : false,
              child: Container(
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                  color: Color(0xFFF8F8F8),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Builder(builder: (context) {
                  //第三方平台结算服务费
                  double textAllPrice = 0;
                  textAllPrice = ObjectUtil.isNotEmpty(feeModel)
                      ? NumUtil.multiply(
                          double.parse(_controller.text),
                          double.parse(feeModel.trilateralPlatformFee ?? "0") *
                              0.01)
                      : 0.00;
                  textAllPrice =
                      NumUtil.getNumByValueDouble(textAllPrice, 2)!.toDouble();
                  //三方平台转账手续费
                  double tripartitePrice = 0;
                  tripartitePrice = ObjectUtil.isNotEmpty(feeModel)
                      ? NumUtil.multiply(
                          double.parse(_controller.text),
                          double.parse(feeModel.trilateralPlatformTransferFee ??
                                  "0") *
                              0.01)
                      : 0.00;
                  tripartitePrice =
                      NumUtil.getNumByValueDouble(tripartitePrice, 2)!
                          .toDouble();
                  //创作者版权分成
                  double framerPrice = 0;
                  framerPrice = ObjectUtil.isNotEmpty(widget.model)
                      ? NumUtil.multiply(
                          double.parse(_controller.text),
                          double.parse(widget.model.specialAlbumRate ?? "0") *
                              0.01)
                      : 0.00;
                  framerPrice =
                      NumUtil.getNumByValueDouble(framerPrice, 2)!.toDouble();

                  print("版权---${widget.model.toJson()}");

                  //平台服务费用
                  double platformPrice = 0;
                  platformPrice = ObjectUtil.isNotEmpty(feeModel)
                      ? NumUtil.add(double.parse(feeModel.aisleFee ?? "0"),
                          double.parse(feeModel.chainFee ?? "0"))
                      : 0.00;
                  platformPrice = ObjectUtil.isNotEmpty(feeModel)
                      ? NumUtil.add(platformPrice,
                          double.parse(feeModel.platformFee ?? "0"))
                      : 0.00;
                  double platformPricevalue = 0;
                  platformPricevalue = ObjectUtil.isNotEmpty(feeModel)
                      ? NumUtil.multiply(
                          double.parse(_controller.text), platformPrice * 0.01)
                      : 0.00;
                  platformPricevalue =
                      NumUtil.getNumByValueDouble(platformPricevalue, 2)!
                          .toDouble();

                  //实际到账
                  double realityPrice = 0;
                  realityPrice = double.parse(_controller.text) -
                      textAllPrice -
                      tripartitePrice -
                      platformPricevalue -
                      framerPrice;

                  return Column(
                    children: [
                      priceItem("总售价", "¥${_controller.text}"),
                      SizedBox(
                        height: 15,
                      ),
                      // priceItem("三方平台结算服务费", "-¥$textAllPrice"),
                      priceItem(
                          "三方支付手续费", "-¥${textAllPrice + tripartitePrice}"),
                      SizedBox(
                        height: 15,
                      ),
                      priceItem(
                          "平台服务费（$platformPrice%）", "-¥$platformPricevalue"),
                      SizedBox(
                        height: 15,
                      ),
                      priceItem(
                          "创作者版权分成（${widget.model.specialAlbumRate ?? "0.00"}%）",
                          "-¥$framerPrice"),
                      SizedBox(
                        height: 15,
                      ),
                      // priceItem(
                      //     "三方平台转账手续费（${feeModel.trilateralPlatformTransferFee ?? "0.00"}%）",
                      //     "-¥$tripartitePrice"),
                      SizedBox(
                        height: 15,
                      ),
                      Container(
                        width: double.infinity,
                        height: 1,
                        color: Color(0xFFEAEAEA),
                      ),
                      SizedBox(
                        height: 15,
                      ),
                      Row(
                        children: [
                          Text(
                            "实际到账",
                            style: TextStyle(
                              fontSize: 14,
                              color: Global.kTheme.textPrimary1,
                            ),
                          ),
                          Spacer(),
                          Text(
                            "¥${realityPrice.toStringAsFixed(2)}",
                            style: TextStyle(
                                fontSize: 14,
                                color: Global.kTheme.textPrimary1,
                                fontFamily: Global.myDINFont),
                          ),
                        ],
                      ),
                      SizedBox(
                        height: 10,
                      ),
                    ],
                  );
                }),
              ),
            )
          ],
        ));
  }

  Widget priceItem(String left, String right) {
    return Row(
      children: [
        Text(
          left,
          style: TextStyle(
            fontSize: 12,
            color: Global.kTheme.inputHint1,
          ),
        ),
        Spacer(),
        Text(
          right,
          style: TextStyle(
            fontSize: 12,
            color: Global.kTheme.textPrimary1,
          ),
        ),
      ],
    );
  }
}
